import { HOST } from '@/config';
import { useUserStoreWithOut } from '@/store/modules/user';
const userStore = useUserStoreWithOut();

export async function downloadFile(url, method = 'GET', params = null) {
  const accessToken: any = userStore.getToken;
  const headers = {
    token: accessToken,
    'content-type': 'application/json'
  };
  const response = await fetch(`${HOST}${url}`, { headers, method, body: params ? JSON.stringify(params) : null });
  if (!response.ok) {
    throw new Error('请求失败');
  }
  const blob = await response.blob();
  // 获取文件名
  const dispositionHeader = response.headers.get('content-disposition') || '';
  const list = dispositionHeader.split('=');
  const filename =
    window
      .decodeURIComponent(`${list[list.length - 1]}`)
      .replace(/(utf-8|')/g, '')
      .replace(/(")/g, '') || '文件.xlsx';
  // 创建a标签，点击下载
  const fileUrl = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = fileUrl;
  link.download = filename;
  link.click();
  window.URL.revokeObjectURL(fileUrl);
}
